package cn.zsc.netdisk.service;

import cn.zsc.netdisk.common.AdviseType;
import cn.zsc.netdisk.common.Paths;
import cn.zsc.netdisk.common.UserInfo;
import cn.zsc.netdisk.pojo.Advise;
import cn.zsc.netdisk.pojo.Share;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * 定时任务
 * @author ccying
 * @date 2021/3/10
 */
@Component
@Slf4j
public class ScheduledService implements InitializingBean {
    @Resource
    private FileService fileService;
    @Resource
    private ShareService shareService;
    @Resource
    private AdviseService adviseService;


    /**
     * 每天凌晨1点执行
     * 删除分享文件压缩包
     * */
    @Scheduled(cron = "0 0 1 * * ?")
    @Async
    public void deleteTempShareFile() {
        System.out.println("*************************************************");
        log.info("定时执行：删除分享文件压缩包");
        try {
            String[] files = new File(Paths.TEMP_ROOT_PATH_SHARE).list();
            for (String file : files) {
                //删除分享文件
                this.fileService.deleteFile(Paths.TEMP_ROOT_PATH_SHARE + file);
            }
            //生成通知
            String[] uids = shareService.findAllShareUid();
            for (int i = 0; i < uids.length; i++) {
                Advise advise = adviseService.to(uids[i], AdviseType.SHARE_FILE_LISTENER,null);
                this.adviseService.add(advise);
            }
            //删除所有分享链接
            this.shareService.deleteAll();
        } catch (Exception e) {
            log.error(e.toString());
        }
    }

    /**
     * 每隔十分钟执行
     * 删除下载文件压缩包
     * */
    @Async
    @Scheduled(cron = "0 */10 * * * ?")
    public void deleteTempDownloadFile() {
        System.out.println("*************************************************");
        log.info("定时执行：删除下载文件压缩包");
        try {
            String[] files = new File(Paths.TEMP_ROOT_PATH_DOWN).list();
            for (String file : files) {
                this.fileService.deleteFile(Paths.TEMP_ROOT_PATH_DOWN + file);
            }
        } catch (IOException e) {
            log.error(e.toString());
        }
    }

    @Override
    public void afterPropertiesSet(){
        this.deleteTempDownloadFile();
        this.deleteTempShareFile();
    }
}
